package com.rain.codemother.core.saver;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.rain.codemother.ai.model.HtmlCodeResult;
import com.rain.codemother.constant.AppConstant;
import com.rain.codemother.exception.BusinessException;
import com.rain.codemother.exception.ErrorCode;
import com.rain.codemother.model.enums.CodeGenTypeEnum;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;

public abstract class CodeFileSaverTemplate<T>{

    // 文件保存根目录
//    private static final String FILE_SAVE_ROOT_DIR = System.getProperty("user.dir") + "/tmp/code_output";

    // 文件保存根目录
    protected static final String FILE_SAVE_ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;

    public final File saveCode(T result,Long appId) {
        validFile(result);
        String baseDirPath = buildUniqueDir(appId);
        saveFiles(result, baseDirPath);
        return new File(baseDirPath);
    }

    protected  void validFile(T result) {
        if (result == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结果对象不能为空");
        }
    }
    protected final String buildUniqueDir(Long appId){
        if(appId==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "appId不能为空");
        }
        String bizType=getCodeType().getValue();
        String uniqueDirName = StrUtil.format("{}_{}", bizType, appId);
        String dirPath = FILE_SAVE_ROOT_DIR + File.separator + uniqueDirName;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }
    protected final void writeToFile(String baseDirPath, String filename, String content) {
        if(StringUtils.isNotBlank(content)){
            String filePath = baseDirPath + File.separator + filename;
            FileUtil.writeString(content, filePath, StandardCharsets.UTF_8);
        }
    }
    protected abstract CodeGenTypeEnum getCodeType();
    protected abstract void saveFiles(T result, String baseDirPath);

}
